package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import com.sky.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    private final AddressBookMapper addressBookMapper;

    @Autowired
    public AddressBookServiceImpl(AddressBookMapper addressBookMapper) {
        this.addressBookMapper = addressBookMapper;
    }

    /**
     * 新增地址
     *
     * @param addressBook 地址body
     */
    @Override
    public void save(AddressBook addressBook) {
        addressBook.setUserId(ThreadLocalUtil.get());
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 查询当前登录用户的所有地址信息
     *
     * @return 当前登录用户的所有地址信息
     */
    @Override
    public List<AddressBook> list(AddressBook addressBook) {
        return addressBookMapper.list(addressBook);
    }

    /**
     * 根据id修改地址
     *
     * @param addressBook body
     */
    @Override
    public void updateAddressBook(AddressBook addressBook) {
        addressBook.setUserId(ThreadLocalUtil.get());
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id 地址ID
     */
    @Override
    public void deleteAddressBook(Long id) {
        addressBookMapper.delete(id);
    }

    /**
     * 根据id查询地址
     *
     * @param id 地址ID
     * @return 地址实体
     */
    @Override
    public AddressBook findById(Long id) {
        return addressBookMapper.getById(id);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook body
     */
    @Override
    @Transactional
    public void setDefault(AddressBook addressBook) {
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBook.setUserId(ThreadLocalUtil.get());
        addressBookMapper.updateIsDefaultByUserId(addressBook);

        addressBook.setIsDefault(StatusConstant.ENABLE);
        addressBookMapper.update(addressBook);
    }


}
